import {
    CodeAction,
    CodeActionContext,
    CodeActionKind,
    Position
} from "vscode-languageserver";
import { createWorkspaceEditorInsertContent } from "./util";

const actionMessages = {
    setFileAsMetadata: "设定文件类型为'metadata'",
    setFileAsScriptMrs: "设定文件类型为'mrs script'",
    setFileAsScriptDms: "设定文件类型为'dms script'",
    setFileIgnoreTypeError: "忽略当前文件的类型错误",
    setOptionImplicit: "设置允许隐式声明变量",
};

function createCodeAction(uri: string, title: string, text: string, kind: string) {
    return CodeAction.create(title, createWorkspaceEditorInsertContent(uri, Position.create(0, 0), text), kind);
}

export async function provideCodeAction(context: CodeActionContext, uri: string): Promise<CodeAction[]> {
    if (context.diagnostics.length === 0) {
        return [];
    }
    const actions: CodeAction[] = [];

    for (const diag of context.diagnostics) {
        if (!diag.code) {
            continue;
        }
        // script
        if (diag.code < 4000) {
            actions.push(createCodeAction(uri, actionMessages.setFileAsMetadata, "'metadata\n", CodeActionKind.QuickFix));
        }
        // metadata
        else if (diag.code > 4000) {
            actions.push(
                createCodeAction(uri, actionMessages.setFileAsScriptMrs, "'script-mrs\n", CodeActionKind.QuickFix),
                createCodeAction(uri, actionMessages.setFileAsScriptDms, "'script-dms\n", CodeActionKind.QuickFix),
            );
        }
        // 变量未声明
        if (diag.code === 3002) {
            actions.push(createCodeAction(uri, actionMessages.setOptionImplicit, "Option Implicit\n", CodeActionKind.QuickFix));
        }
    }

    actions.push(
        createCodeAction(uri, actionMessages.setFileIgnoreTypeError, "'ignore-type-error\n", CodeActionKind.QuickFix),
    );

    return actions;
}
